//
//  DWJTabBar.swift
//  weibo
//
//  Created by 代伟佳 on 16/4/16.
//  Copyright © 2016年 代伟佳. All rights reserved.
//

import UIKit

protocol DWJTabBarDelegate: NSObjectProtocol {

    // 协议方法
    func composeButtonClick()
}

class DWJTabBar: UITabBar {
    
    // 声明一个代理 需要用weak修饰 但是要遵守基协议
    weak var DWJDelegate:DWJTabBarDelegate?

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUpUI()
    }
    
    //  如果重写了initFrame 必须实现这个方法
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 监听事件
    @objc private func composeButtonClick() {
    
        DWJDelegate?.composeButtonClick()
    }
    
    
    
    // MARK: - 设置控件
    func setUpUI() {
        
        addSubview(composeButton)
    }
    
    // MARK: - 设置子控件布局
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        // 设置tabBar身上子控件的宽度
        let width = kWIDTH / 5
        var index: CGFloat = 0
        
        for value in self.subviews {

            
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!) {
            
                // 遍历获取tabBar所有的UITabBarButton
//                print(value)
                
                // 设置value的x
                value.frame.origin.x = index * width
                // 设置value的宽
                value.frame.size.width = width
                
                index++
                if index == 2 {
                
                    index++
                }
            }

        }
        
        
        // 设置中间按钮的位置
        composeButton.center.x = self.frame.size.width * 0.5
        composeButton.center.y = self.frame.size.height * 0.5
        
    }
    
    
    
    // MARK: - 懒加载控件
    private lazy var composeButton: UIButton = {
        
        let button = UIButton()
        
        // 添加点击事件
        button.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        button.sizeToFit()
        
        return button
        
    }()

}
